package com.gecba.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONArray;
import com.gecba.system.service.CommonService;
import com.gecba.system.vo.DuplicateCheckVo;
import com.gecba.system.vo.SelectOptionsVo;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

@Service
public class CommonServiceImpl implements CommonService {

    @Autowired
    private EntityManager entityManager;


    @Override
    @Transactional
    @SneakyThrows
    public List<SelectOptionsVo> selectOptions(SelectOptionsVo selectOptionsVo) {
        List<SelectOptionsVo> collect = new ArrayList<>();
        String stringBuilder = "select " +
                selectOptionsVo.getValueField() + " as value, " +
                selectOptionsVo.getTextField() + " as text " +
                " from " + selectOptionsVo.getTableName();
        Query nativeQuery = entityManager.createNativeQuery(stringBuilder);
        JSONArray jsonArray = new JSONArray(nativeQuery.getResultList());
        if(CollectionUtil.isNotEmpty(jsonArray)){
            collect = jsonArray.stream().map(arr -> {
                SelectOptionsVo optionsVo = new SelectOptionsVo();
                JSONArray array = new JSONArray(arr);
                optionsVo.setValue(array.getStr(0));
                optionsVo.setText(array.getStr(1));
                return optionsVo;
            }).collect(Collectors.toList());
        }
        return collect;
    }

    /**
     * 字段重复校验
     *
     * @param duplicateCheckVo
     * @return true 字段值存在  false 字段值不存在
     */
    @Override
    public boolean doDuplicateCheck(DuplicateCheckVo duplicateCheckVo) {
        String sql = "select id from " +
                duplicateCheckVo.getTableName() +
                " where " + duplicateCheckVo.getValueField() +
                " = '" + duplicateCheckVo.getValue() +"'";
        if(Objects.nonNull(duplicateCheckVo.getId())){
            sql += " and id != " + duplicateCheckVo.getId();
        }
        Query nativeQuery = entityManager.createNativeQuery(sql);
        JSONArray jsonArray = new JSONArray(nativeQuery.getResultList());
        return CollectionUtil.isNotEmpty(jsonArray);
    }
}
